package rmi;

import implentation.Invoker;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.Remote;
import java.rmi.server.RemoteStub;
import java.rmi.server.UnicastRemoteObject;

public class RMIServer   implements Runnable {
	InetAddress adress;
	int port;

	public RMIServer(InetAddress adress, int port) {
		super();
		this.adress = adress;
		this.port = port;
	}
	/**
	 * The server socket
	 */
	private ServerSocket socketServer;

	/**
	 * The input stream object
	 */
	private ObjectInputStream input = null;

	/**
	 * The output stream object
	 */
	private ObjectOutputStream output = null;

	/**
	 * Boolean is running or not
	 */
	private boolean isRunning;

	/**
	 * Constructor
	 * 
	 * @param adress
	 * @param port
	 */
	

	/**
	 * The runnable method
	 * 
	 * @Override
	 */
	public void run() {
		this.isRunning = true;
		
		try {
			Invoker traitement = new Invoker();
			//UnicastRemoteObject.unexportObject(traitement, false);
			Remote stub = UnicastRemoteObject.exportObject(traitement, 0);
			
			Socket socket = null;
			
			while (this.isRunning) {
				this.socketServer = new ServerSocket(this.port, 50, this.adress);
				socket = this.socketServer.accept();

				this.output = new ObjectOutputStream(socket.getOutputStream());
				this.input = new ObjectInputStream((socket.getInputStream()));

				while (true) {
					try {
						// Receive a request
						String requestRecu = (String) this.input.readObject();
				        System.out.println("Serveur : receive request");
				        
						// Send the stub
				        System.out.println("Serveur: send stub");
						//this.output.writeObject(stub);
				        this.output.writeObject(stub);
						
						socket.close();
					} catch (Exception se) {
						break;
					}
				}
				socketServer.close();
			}
		} catch (Exception se) {
			System.err.println("Serveur : exception " + se);
		}
	}

	

	public boolean isRunning() {
		return isRunning;
	}

	public void setRunning(boolean isRunning) {
		this.isRunning = isRunning;
	}
	
	
	
	
	
}